package com.suneee.cloud.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suneee.base.config.ServiceConfig;
import com.suneee.base.context.OnlineUser;
import com.suneee.base.context.Session;
import com.suneee.base.filter.UserFilter;
import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.UserThreadLocal;
import com.suneee.cloud.admin.dao.AdministratorDao;
import com.suneee.cloud.admin.resources.AdminError;
import com.suneee.component.cache.CacheUtils;
import com.suneee.component.cache.thread.ThreadLocalCache;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.DateUtils;
import com.suneee.core.util.MD5Utils;
import com.suneee.enterprise.entity.Enterprise;
import com.suneee.enterprise.service.EnterpriseService;
import com.suneee.permission.entity.Permission;
import com.suneee.permission.utils.PermissionWrapUtil;
import com.suneee.role.entity.Role;
import com.suneee.role.service.RoleService;
import com.suneee.sso.admin.entity.Administrator;
import com.suneee.sso.admin.service.IAdminUserLoginService;
import com.suneee.web.util.CookieUtils;

@Service("api-userLogin")
public class UserLoginServiceImpl implements UserLoginService {

	@Autowired
	private IAdminUserLoginService iAdminUserLoginService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private EnterpriseService enterpriseService;
	
	@Autowired
	private AdministratorDao administratorDao;
	
	@Override
	public Administrator login(String validateCode,String account, String password, String sessionId, String clientIp, String appCode) {
		
		Assert.notEmpty(account, "account");
		Assert.notEmpty(password, "password");
//		Assert.notEmpty(validateCode, "validateCode");
		
		HttpServletRequest request = (HttpServletRequest)ThreadLocalCache.getObject(UserFilter.REQUEST);
	    HttpServletResponse response = (HttpServletResponse)ThreadLocalCache.getObject(UserFilter.RESPONSE);
		Session session = UserThreadLocal.getSession();
		String logSessionId = "suneeeCloud"+session.getSessionId();
		
		//验证码校验
//		String code = (String) request.getSession().getAttribute("rand");
//		if(!validateCode.toLowerCase().equals(code)){
//			throw ErrorUtils.wrap(AdminError.VERIFICATION_CODE_ERROR);
//		}
		
		// 登录检查，获取信息
		Administrator admin = iAdminUserLoginService.login(account, MD5Utils.md5(password),logSessionId, "", ""); 
		
		if (admin == null) {
			throw ErrorUtils.wrap(AdminError.ACCOUNT_PASSWORD_MISMATCH);
		}
		
		String isEnable = admin.getEnabled();
		if("false".equals(isEnable)|| "0".equals(isEnable)){
			throw ErrorUtils.wrap(AdminError.ACCOUNT_DISABLE);
		}
		
	    Enterprise enterprise = enterpriseService.get(admin.getEnterpriseCode());
	    if(enterprise != null && enterprise.getType().equals(Enterprise.CLIENT)){
	    	throw ErrorUtils.wrap(AdminError.LOGIN_CLOUD_ERROR);
	    }
		
//		List<Role> roleList = roleService.adminRoleList(admin.getAdminId());
//		admin.setRoleList(roleService.adminRoleList(admin.getAdminId()));
		// 获取登录管理员权限信息、把菜单包装成树形结构
	    admin.setPlatformFlag(true);
		this.wrapRolePermission(admin,admin.getPlatformFlag());
		
		
		//获取管理员企业信息
		admin.setEnterprise(enterpriseService.get(admin.getEnterpriseCode()));
		
		OnlineUser onlineUser = new OnlineUser(session.getSessionId(),admin,DateUtils.getCurrentTimestamp(), session.getIp(),session.getDeviceType());
		session.setOnlineUser(onlineUser);
		CacheUtils.get(Session.class).update(session.getSessionId(),session);
		
		
	    CookieUtils.setCookie(request,response, UserFilter.COOKIE_SESSION, session.getSessionId());
		
	    
	    admin.setSessionId(session.getSessionId());
		admin.setPassword("");
		String fileUrl = ContextHelper.getBean("serviceConfig", ServiceConfig.class).getFileUrl();
		admin.setFileUrl(fileUrl);
		
		return admin;
	}
	
	@Override
	public Administrator loginEn(String validateCode,String enterpriseName, String account, String password, String sessionId, String clientIp, String appCode) {
		Assert.notEmpty(account, "account");
		Assert.notEmpty(password, "password");
		Assert.notEmpty(enterpriseName, "enterpriseName");
//		Assert.notEmpty(validateCode, "validateCode");
		HttpServletRequest request = (HttpServletRequest)ThreadLocalCache.getObject(UserFilter.REQUEST);
	    HttpServletResponse response = (HttpServletResponse)ThreadLocalCache.getObject(UserFilter.RESPONSE);
		
		Session session = UserThreadLocal.getSession();
		String logSessionId = "suneeeCloud"+session.getSessionId();
		
		//验证码校验
//		String code = (String) request.getSession().getAttribute("rand");
//		if(!validateCode.toLowerCase().equals(code)){
//			throw ErrorUtils.wrap(AdminError.VERIFICATION_CODE_ERROR);
//		}
		
		//查询企业是否存在
		Enterprise enterprise = enterpriseService.getByName(enterpriseName);
		if (enterprise == null) {
			throw ErrorUtils.wrap(AdminError.ENTERPRISE_NULL);
		}
		
		String enterpriseCode = enterprise.getEnterpriseCode();
		//调用认证服务接口 
		Administrator admins = iAdminUserLoginService.loginEn(enterpriseCode, account, MD5Utils.md5(password), logSessionId, clientIp, appCode);
		
		if (admins == null) {
			throw ErrorUtils.wrap(AdminError.ACCOUNT_PASSWORD_MISMATCH);
		}
		
		Administrator admin = administratorDao.select(admins.getAdminId());
		
		String isEnable = admin.getEnabled();
		if(isEnable.equals("0")){
			throw ErrorUtils.wrap(AdminError.ACCOUNT_DISABLE);
		}
		
		if(enterprise != null && enterprise.getType().equals(Enterprise.SYSTEM)){
	    	throw ErrorUtils.wrap(AdminError.LOGIN_EN_ERROR);
	    }
		
		// 获取用户权限信息
//		admin.setRoleList(roleService.adminRoleList(admin.getAdminId()));
		// 获取登录管理员权限信息、把菜单包装成树形结构
		admin.setPlatformFlag(false);
		this.wrapRolePermission(admin,admin.getPlatformFlag());
		
		//获取管理员企业信息
		admin.setEnterprise(enterpriseService.get(admin.getEnterpriseCode()));
		
		OnlineUser onlineUser = new OnlineUser(session.getSessionId(),admin,DateUtils.getCurrentTimestamp(), session.getIp(),session.getDeviceType());
		session.setOnlineUser(onlineUser);
		CacheUtils.get(Session.class).update(session.getSessionId(),session);
		
		
	    CookieUtils.setCookie(request,response, UserFilter.COOKIE_SESSION, session.getSessionId());
		
	    admin.setSessionId(session.getSessionId());
		admin.setPassword("");
		String fileUrl = ContextHelper.getBean("serviceConfig", ServiceConfig.class).getFileUrl();
		admin.setFileUrl(fileUrl);
		return admin;
	}

	@Override
	public void loginOut() {
		 OnlineUser onlineUser = UserThreadLocal.getOnlineUser();
         if (null != onlineUser && null != onlineUser.getAdmin()) {
            Session session = UserThreadLocal.getSession();
            
            iAdminUserLoginService.loginOut(session.getSessionId());//调用远程接口删除redis缓存
            
            session.setOnlineUser(null);
            CacheUtils.get(Session.class).remove(session.getSessionId());
            HttpServletRequest request = (HttpServletRequest)ThreadLocalCache.getObject(UserFilter.REQUEST);
    	    HttpServletResponse response = (HttpServletResponse)ThreadLocalCache.getObject(UserFilter.RESPONSE);
    	    Cookie cookie = new Cookie(UserFilter.COOKIE_SESSION,session.getSessionId());
    	    CookieUtils.deleteCookie(request,response,cookie);
        }
	}

	@Override
	public Boolean checkLogin() {
		Session session = UserThreadLocal.getSession();
    	Session caechSession = CacheUtils.get(Session.class).get(session.getSessionId());
    	if(caechSession!=null && caechSession.getOnlineUser()!=null){
    	    return true;
    	}
        return false;
	}

	/**
	 * 获取用户拥有的角色、权限，包装菜单成树形结构
	 * @param admin
	 * @param flag true:平台端；false:企业端
	 */
	private void wrapRolePermission(Administrator admin,Boolean flag){
		List<Role> roleList = roleService.adminRoleList(admin.getAdminId(),flag);
		admin.setRoleList(roleList);
		if(roleList != null && !roleList.isEmpty()){
			Map<Integer,Permission> temp = new HashMap<>();
			for(Role role : roleList){
				List<Permission> permissionList = role.getPermissionList();
				if(permissionList != null && !permissionList.isEmpty()){
					for(Permission permission : permissionList){//去重
						if(temp.get(permission.getPermissionId()) == null){
							temp.put(permission.getPermissionId(), permission);
						}
					}
				}
			}
			if(!temp.isEmpty()){//包装
				if(flag)
					admin.setMenuList(PermissionWrapUtil.treeWrap(new ArrayList<Permission>(temp.values())).get(PermissionWrapUtil.ROOT_FLAG));
				else
					admin.setMenuList(PermissionWrapUtil.enterpriseTreeWrap(new ArrayList<Permission>(temp.values())).get(PermissionWrapUtil.ROOT_FLAG));
			}
		}
		
	}
}
